<?php
class AdminsController extends AppController {
	public $helpers = array (
			'Html',
			'Form',
			'Session',
			'Paginator' 
	);
	
	// public function manage() {
	
	// $logined = null;
	// if($this->Session->check('AdminLogin')) {
	// $logined = $this->Session->read('AdminLogin');
	// }
	// //print_r($logined);
	// //$this->autoRender = false;
	// if(!$logined) {
	// $this->Session->setFlash('Please login!','default',array('class' => 'alert alert-info'));
	// return $this->render('/login/login');
	// }
	// // $this->set('admin',$this->Admin->findByAdminid($logined));
	// $this->loadModel('Post');
	// $this->set('list',$this->Post->find('all',array(
	// 'conditions' => array('Post.Admin_id' => $logined['Admin']['AdminID']),
	// 'fields' => 'created'
	// )));
	// $this->paginate = array(
	// 'conditions' => array('Post.Admin_id' => $logined['Admin']['AdminID']),
	// 'limit' => $this->Session->read('limit'),
	// 'order' => 'Post.modified DESC'
	// );
	// try {
	// $posts = $this->paginate('Post');
	// $this->set('posts',$posts);
	// } catch (NotFoundException $e) {
	// $this->Session->setFlash('Page not found!!!','default',array('class' => 'alert alert-warning'));
	// return $this->redirect(array('action' => 'manage'));
	// }
	// }
	public function manage($target = null) {
		//session check authen on manage.ctp
		$this->Session->write ( 'authen', false );
		
		//check login & params
		$logined = null;
		if ($this->Session->check ( 'AdminLogin' )) {
			$logined = $this->Session->read ( 'AdminLogin' );
		} else {
			// hungdv7 check session
			/*
			 * $this->Session->setFlash('Please login to access this function!','default',array('class' => 'alert alert-danger')); return $this->redirect(array('controller'=>'posts','action'=>'index'));
			 */
		}
		if (! $target) {
			$this->Session->setFlash ( 'System error!', 'default', array (
					'class' => 'alert alert-danger' 
			) );
			return $this->redirect ( array (
					'controller' => 'posts',
					'action' => 'index' 
			) );
		}
		//check whether user exist
		$this->checkTarget($target);
		
		
		if ($logined && ($target == $logined ['Admin'] ['AdminID'])) {
			$this->Session->write ( 'authen', true ); //user has full authority on manage.ctp
		}
		
		//set data for manage.ctp
		$this->set ( 'user', $this->Admin->findByAdminid ( $target ) );
		$this->loadModel ( 'Post' );
		$this->set ( 'list', $this->Post->find ( 'all', array (
				'conditions' => array (
						'Post.Admin_id' => $target 
				),
				'fields' => 'created' 
		) ) );
		
		//QuanNNM search
		
		//new ton tai session search normal
		if($this->Session->check('SearchCondition')){
			//lay gia tri session search normal
			$searchCondition = $this->Session->read('SearchCondition');
			
			//lay so dong tim kiem duoc ung voi gia tri search normal
			$numRow = $this->Post->find ( 'count', array (
					'conditions' => array ('Post.Admin_id' => $target,
							'Post.title LIKE' => '%' . $searchCondition . '%'
					),
					'order' => array (
							'Post.modified DESC'
					)
			) );
			
			//neu so dong lay duoc < 1
			if($numRow < 1){
				//set thong bao loi khong tim thay du lieu
				$this->Session->setFlash ( 'No data found!', 'default', array (
						'class' => 'alert alert-danger'
				) );
			}else{
				//neu so dong lay duoc >= 1, set thong bao tim thay n dong du lieu
				$this->Session->setFlash ( 'Found '.$numRow.' results!', 'default', array (
						'class' => 'alert alert-success'
				) );
			}
			
			//set bien paginate la ket qua select theo session search normal, voi limit la session 'limit'
			$this->paginate = array(
					'conditions' => array('Post.Admin_id' => $target, 'Post.title LIKE' => '%'.$searchCondition.'%'),
					'limit' => $this->Session->read('limit'),
					'order' => 'Post.modified DESC'
			);
				
		}
		//neu khong ton tai session normal search
		else{
			//set bien paginate la ket qua select toan bo post title voi limit la session 'limit' 
			$this->paginate = array(
					'conditions' => array('Post.Admin_id' => $target),
					'limit' => $this->Session->read('limit'),
					'order' => 'Post.modified DESC'
			);
		}
		//QuanNNM ^
		
		
// 		$this->paginate = array (
// 				'conditions' => array (
// 						'Post.Admin_id' => $target 
// 				),
// 				'limit' => $this->Session->read ( 'limit' ),
// 				'order' => 'Post.modified DESC' 
// 		);

		// pagination
		try {
			$posts = $this->paginate ( 'Post' );
			$this->set ( 'posts', $posts );
		} catch ( NotFoundException $e ) {
			$this->Session->setFlash ( 'Page not found!!!', 'default', array (
					'class' => 'alert alert-warning' 
			) );
			return $this->redirect ( array (
					'controller' => 'posts',
					'action' => 'index' 
			) );
		}
		
		// get data for graph
		// find all the date this user create post, group by created date
		$results = $this->Post->find ( 'all', array (
				'conditions' => array (
						'Post.Admin_id' => $target 
				),
				'fields' => array (
						'DATE(Post.created) AS created',
						'COUNT(*) AS quantity' 
				),
				'group' => array (
						'DATE(Post.created)' 
				),
				'order' => array (
						'DATE(Post.created) ASC' 
				) 
		) );
		
		// group the result again, this time by month_year
		$monthYearGroup = array ();
		App::uses ( 'CakeTime', 'Utility' );
		$dummyStr = "";
		$tempCount = 0;
		
		for($i = 0; $i < sizeof ( $results ); $i ++) {
			$rTime = CakeTime::format ( $results [$i] [0] ['created'], '%B_%Y' );
			
			//check whether the value month_year is stored in $monthYearGroup array, use another temp string
			if (strpos ( $dummyStr, $rTime ) === false) {
				$dummyStr = $dummyStr . $rTime . ' ';
				
				// sum the quantity of equal-month_year records
				for($j = $i; $j < sizeof ( $results ); $j ++) {
					$rTimeChild = CakeTime::format ( $results [$j] [0] ['created'], '%B_%Y' );
					
					if ($rTimeChild == $rTime) {
						$tempCount = $tempCount + $results [$j] [0] ['quantity'];
					} else {
						break;
					}
				}
				
				// store the new month_year time and quantity into array
				array_push ( $monthYearGroup, array (
						'dateTime' => $rTime,
						'quantity' => $tempCount 
				) );
				$tempCount = 0;
			}
		}
		
		//json encode for data chart
		$chartData ['cols'] = array (
				array (
						'id' => 'created',
						'label' => 'Date',
						'type' => 'string' 
				),
				array (
						'id' => 'quantity',
						'label' => 'Posted',
						'type' => 'number' 
				) 
		);
		foreach ( $monthYearGroup as $result ) {
			// $time = strtotime ( $result [0] ['created'] );
			// $dateJs = 'Date(' . date ( "Y", $time ) . ', ' . (date ( 'n', $time ) - 1) . ', ' . date ( 'j', $time ) . ')';
			$row = array (
					'c' => array (
							array (
									'v' => $result ['dateTime'] 
							),
							array (
									'v' => $result ['quantity'] 
							) 
					) 
			);
			$chartData ['rows'] [] = $row;
		}
		$this->set ( 'chartData', json_encode ( $chartData ) );
	}
	public function add() {
		//check login before redirect to add in posts controller
		$logined = null;
		if ($this->Session->check ( 'AdminLogin' )) {
			$logined = $this->Session->read ( 'AdminLogin' );
		}
		if (! $logined) {
			$this->Session->setFlash ( 'Please login!', 'default', array (
					'class' => 'alert alert-info' 
			) );
			return $this->render ( '/login/login' );
		}
		$this->layout = "postLayout";
		// $this->set('admin',$this->Admin->findByAdminid($logined));
		return $this->render ( '/posts/add' );
	}
	
	
	//action chuan bi data de vao trang quan ly cua user login, truyen vao id cua user
	public function manageclick($target = null){
		//neu khong ton tai id user truyen vao
		if(!$target) {
			//show thong bao loi va quay lai trang chu
			$this->Session->setFlash('System error!','default',array('class' => 'alert alert-danger'));
			return $this->redirect(array('controller'=>'posts','action'=>'index'));
		}
		
		//xoa session search normal truoc khi vao action manage
		$this->Session->delete('SearchCondition');
		
		//chuyen tiep qua action manage, voi tham so id user truyen qua
		return $this->redirect(array('action' => 'manage', $target));
	}
	
	public function checkTarget($id = null) {
		//check params
		if(!$id) {
			$this->Session->setFlash('System error!','default',array('class' => 'alert alert-danger'));
			return $this->redirect(array('controller'=>'posts','action'=>'index'));
		}
		//check user exist
		$check = $this->Admin->find('all',array('conditions' => array('Admin.AdminID' => $id)));
		if(!$check) {
			$this->Session->setFlash('This user does not exist!','default',array('class' => 'alert alert-danger'));
			return $this->redirect(array('controller'=>'posts','action'=>'index'));
		}
	}
}